import Vue from 'vue';
import VueRouter from 'vue-router';
import cookies from 'vue-cookies';

// 注册路由插件
Vue.use(VueRouter);

//
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home/index.vue'),
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register/index.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login/index.vue'),
  },
  // {
  //   path: '/',
  //   redirect: '/login',
  // },
  { path: '*', component: () => import('../views/404.vue') },
];
const router = new VueRouter({
  mode: 'history',
  // base: process.env.BASE_URL,
  routes,

  // beforeRouteLeave(to, from, next) {
  //   to.meta.keepAlive = true;
  //   next();
  // },
});

router.beforeEach((to, from, next) => {
  // to 到哪个path去
  // from 从哪个path来
  // next 通行
  const username = $cookies.get('username') ? true : false;
  if (username) {
    // 已登录
    if (to.path == '/login') {
      next({ path: '/' });
    } else {
      next();
    }
  } else {
    if (to.path != '/login' && to.path != '/register') {
      alert('请先登录');
      next('/login');
    } else {
      next();
    }
  }
});

export default router;
